//
//  MenuView.swift
//  WangPu
//
//  Created by xiaozhi on 15/10/17.
//  Copyright © 2015年 zhixiao. All rights reserved.
//

import UIKit

class MenuView: UIView {
    let titleArray:[String] =   ["商品介绍","商品参数","退款/售后"]
    var selectedBtn:UIButton?
    var line:UIView!
    var buttonEventHandle:((Int)->Void)?
    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
    }
    */
    func  layoutButtons(){
        //        var button:UIButton
        let buttonWidth = bounds.size.width/CGFloat(titleArray.count)
        let buttonHeight = bounds.size.height-1
        for i in 0..<titleArray.count{
            let button = UIButton(frame: CGRectMake(buttonWidth*CGFloat(i), 0, buttonWidth, buttonHeight))
            
            button.setTitle(titleArray[i], forState: UIControlState.Normal)
            button.titleLabel?.font = UIFont.systemFontOfSize(14)
            button.titleLabel?.textAlignment = NSTextAlignment.Center
            button.setTitleColor(commonRedColor, forState: UIControlState.Selected)
            button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
            button.tag = i
            button.addTarget(self, action: "buttonClick:", forControlEvents: UIControlEvents.TouchDown)
            self.addSubview(button)
            if i == 0{
                self.buttonClick(button)
            }
        }

    }
    func buttonClick(button:UIButton){
        if button == selectedBtn{
            return
        }
        var rect = line.frame
        rect.origin.x = button.frame.origin.x
        UIView.animateWithDuration(0.3, delay: 0.0,
            options: UIViewAnimationOptions.LayoutSubviews,
            animations:{
                self.line.frame = rect
            },
            completion:nil)
        buttonEventHandle?(button.tag)
        button.selected = true
        selectedBtn?.selected = false
        selectedBtn = button
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        //        self.backgroundColor = UIColor(patternImage: UIImage(named: "tab-bg")!)
        backgroundColor = UIColor.whiteColor()
        line = UIImageView(frame: CGRectMake(0, frame.size.height-1, bounds.size.width/3, 1))
        line.backgroundColor = commonRedColor
        self.addSubview(line)
        
        self.layoutButtons()
    }
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
}
